package indi.zhifa.engine.core.excel2025.handler.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import indi.zhifa.engine.core.excel2025.annotation.ExcelHandlerAnn;
import indi.zhifa.engine.core.excel2025.entity.IRowData;
import indi.zhifa.engine.core.excel2025.entity.exception.ExcelException;
import indi.zhifa.engine.core.excel2025.enums.EExcelErrorCode;
import indi.zhifa.engine.core.excel2025.handler.IExcelCellHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;

import java.lang.reflect.Field;

@ExcelHandlerAnn(valTypes = {Boolean.class})
@Slf4j
public class BooleanCellHandler implements IExcelCellHandler {
    @Override
    public Object handle(Cell pCell,Class pClass) {
        if(null == pCell){
            return null;
        }
        String strVal = null;
        if(pCell.getCellType() == CellType.STRING){
            strVal = pCell.getStringCellValue();
            strVal = strVal.toUpperCase();
            if(strVal.equals("TRUE")||strVal.equals("1")){
                return true;
            }else if(strVal.equals("FALSE")||strVal.equals("0")){
                return false;
            }
            return null;

        } else if(pCell.getCellType() == CellType._NONE || pCell.getCellType() == CellType.BLANK){
            strVal = null;
            return null;
        }else if(pCell.getCellType() == CellType.BOOLEAN){
            return pCell.getBooleanCellValue();
        }
        return null;
    }

    @Override
    public void fill(Cell pCell, IRowData pRowData, Field pField) throws IllegalAccessException {
        Object data = pField.get(pRowData);
        if(null != data){
            Boolean sData = (Boolean) data;
            if(null != sData){
                pCell.setCellValue(sData);
            }else{
                throw new ExcelException(EExcelErrorCode.CELL_TYPE_FAILED,"对象的字段 "+pField.getName()+" 不是布尔值, \n"+ JSON.toJSONString(pRowData, JSONWriter.Feature.PrettyFormat));
            }
        }
    }
}
